package com.totowoo.shirodemo.controller;

import java.util.UUID;

import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

//import com.totowoo.shirodemo.util.AesEncryptUtil;

@Controller
public class ShiroController {
	private static final Logger log = LoggerFactory.getLogger(ShiroController.class);
	
	@GetMapping("/login.html")
	public String login(Model model, HttpSession session) {

		int hashCode = UUID.randomUUID().hashCode();
		String temporaryKey = String.format("%016d", hashCode);
		model.addAttribute("temporaryKey", temporaryKey);
		session.setAttribute("temporaryKey", temporaryKey);

		return "login";
	}

	@PostMapping("/login.html")
	public String login(String username, String password, Integer remeberMe, HttpSession session) {
		// 0.解密
		/*
		String key = (String) session.getAttribute("temporaryKey");
		try {
			password = AesEncryptUtil.desEncrypt(password, key, key);
		} catch (Exception e1) {
			e1.printStackTrace();
			return "loginError";
		}
		session.removeAttribute("temporaryKey");
		*/
		
		// 1.认证组件
		Subject subject = SecurityUtils.getSubject();

		// 2.将表单提交的用户名和密码封装到token对象内
		UsernamePasswordToken token = new UsernamePasswordToken(username, password);

		if(remeberMe!=null && remeberMe == 1) {
			token.setRememberMe(true);
		}
		
		// 3.调用subject的login方法，进行登录验证
		try {
			subject.login(token);
		} catch (Exception e) {
			//e.printStackTrace();
			log.info("用户[" + username + "]登陆失败.");
			return "loginError";
		}

		// 用户登录日志
		log.info("用户[" + username + "]登陆成功.");
		
		return "redirect:admin/index.html";
		//return "redirect:admin/menu.html";
	}
	
	@GetMapping("/unauthorized.html")
	public String unauthorized() {
		return "unauthorized";
	}
	
	@GetMapping({ "/index", "/" })
	public String index() {
		return "index";
	}
}
